package com.rndemo.rn.event;


import com.facebook.react.bridge.Argument;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.RCTEventEmitter;

/**
 * Created by tzj on 2018/4/26.
 */
public class RefreshChildEvent extends Event<RefreshChildEvent> {
    public static final String NAME = "refreshChild";
    public static final String KEY = "key";
    public static final String INDEX = "index";

    private int viewIndex = -1;
    private int dataIndex = -1;

    public RefreshChildEvent(int viewTag, int viewIndex,int dataIndex) {
        newEvent(viewTag,viewIndex,dataIndex);
    }
    public void newEvent(int viewTag, int viewIndex,int dataIndex){
        super.init(viewTag);
        this.viewIndex = viewIndex;
        this.dataIndex = dataIndex;
    }

    @Override
    public String getEventName() {
        return NAME;
    }
    public int getDataIndex() {
        return dataIndex;
    }
    public int getViewIndex() {
        return viewIndex;
    }

    @Override
    public void dispatch(RCTEventEmitter rctEventEmitter) {
        rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData());
    }

    /**
     * 因为刷新view 不能合并,所以 canCoalesce 设为 true;
     * 然后发现 listView 快速滑动时，会发送好多消息,有些消息是不需要的
     * 查看源码后发现，可以分组合并 getCoalescingKey
     */
    @Override
    public short getCoalescingKey() {
        return (short) this.viewIndex;
    }

    private WritableMap serializeEventData() {
        WritableMap eventData = Argument.createMap();
        eventData.putInt(KEY,getViewIndex());
        eventData.putInt(INDEX,getDataIndex());
        return eventData;
    }

}
